package utils

import (
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"mxshop_api/order_web/global"
)

type PayConfig struct {
	Subject     string
	OutTradeNo  string
	TotalAmount string
}

func Pay(c *PayConfig) string {
	client, err := alipay.New(global.WebConfig.Alipay.AppID, global.WebConfig.Alipay.PrivateKey, false)
	if err != nil {
		zap.S().Errorw("初始化支付宝客户端失败", err)
	}

	err = client.LoadAliPayPublicKey(global.WebConfig.Alipay.AliPublicKey)
	if err != nil {
		zap.S().Errorw("加载支付宝公钥失败", err)
	}

	var p = alipay.TradePagePay{} // page支付方式使用
	p.NotifyURL = global.WebConfig.Alipay.NotifyURL
	p.ReturnURL = global.WebConfig.Alipay.ReturnURL
	p.Subject = c.Subject
	p.OutTradeNo = c.OutTradeNo
	p.TotalAmount = c.TotalAmount
	p.ProductCode = "FAST_INSTANT_TRADE_PAY" // page支付必须使用这个配置

	url, err := client.TradePagePay(p)
	if err != nil {
		zap.S().Errorw("支付失败", err)
	}

	return url.String()
}
